"""
核心功能测试API路由
专门为前端测试Layer 1和Layer 2功能
"""

from fastapi import APIRouter, HTTPException, Depends, status
from typing import List, Dict, Any, Optional
from pydantic import BaseModel
import asyncio

from ....data_layer.data_manager import DataManager
from ....core.interfaces import Document
from ..dependencies import get_container

router = APIRouter(prefix="/api/core-test", tags=["Core Test"])

# 请求和响应模型
class DocumentStoreRequest(BaseModel):
    content: str
    metadata: Dict[str, Any] = {}

class DocumentStoreResponse(BaseModel):
    doc_id: str
    status: str
    message: str

class SearchRequest(BaseModel):
    query: str
    search_type: str = "keyword"  # keyword, vector, hybrid
    top_k: int = 5

class SearchResponse(BaseModel):
    query: str
    results: List[Dict[str, Any]]
    total_count: int
    search_type: str

class HealthCheckResponse(BaseModel):
    status: str
    layer1_status: Dict[str, str]
    layer2_status: Dict[str, str]
    message: str

# 全局数据管理器实例
_data_manager = None

async def get_data_manager():
    """获取数据管理器实例"""
    global _data_manager
    if _data_manager is None:
        _data_manager = DataManager()
        await _data_manager.initialize()
    return _data_manager

@router.get("/health", response_model=HealthCheckResponse)
async def core_health_check():
    """核心功能健康检查"""
    try:
        data_manager = await get_data_manager()
        
        # 检查各组件状态
        layer1_status = {
            "document_store": "OK" if data_manager.document_store else "FAILED",
            "vector_store": "OK" if data_manager.vector_store else "FAILED"
        }
        
        layer2_status = {
            "data_manager": "OK",
            "search_functionality": "OK"
        }
        
        return HealthCheckResponse(
            status="OK",
            layer1_status=layer1_status,
            layer2_status=layer2_status,
            message="Core layers are functioning properly"
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=f"Core health check failed: {str(e)}"
        )

@router.post("/documents", response_model=DocumentStoreResponse)
async def store_document(request: DocumentStoreRequest):
    """存储文档"""
    try:
        data_manager = await get_data_manager()
        
        # 存储文档（暂时跳过向量嵌入以加快测试）
        doc_id = await data_manager.store_document(
            content=request.content,
            metadata=request.metadata,
            generate_embedding=False
        )
        
        return DocumentStoreResponse(
            doc_id=doc_id,
            status="success",
            message=f"Document stored successfully with ID: {doc_id}"
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to store document: {str(e)}"
        )

@router.get("/documents/{doc_id}")
async def get_document(doc_id: str):
    """获取文档"""
    try:
        data_manager = await get_data_manager()
        
        document = await data_manager.document_store.get_document(doc_id)
        if not document:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Document {doc_id} not found"
            )
        
        return {
            "doc_id": document.id,
            "content": document.content,
            "metadata": document.metadata
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve document: {str(e)}"
        )

@router.get("/documents")
async def list_documents():
    """列出所有文档"""
    try:
        data_manager = await get_data_manager()
        
        doc_ids = await data_manager.document_store.list_documents()
        
        # 获取文档摘要信息
        documents = []
        for doc_id in doc_ids[:20]:  # 限制返回数量
            doc = await data_manager.document_store.get_document(doc_id)
            if doc:
                documents.append({
                    "doc_id": doc.id,
                    "metadata": doc.metadata,
                    "content_preview": doc.content[:100] + "..." if len(doc.content) > 100 else doc.content
                })
        
        return {
            "documents": documents,
            "total_count": len(doc_ids)
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to list documents: {str(e)}"
        )

@router.post("/search", response_model=SearchResponse)
async def search_documents(request: SearchRequest):
    """搜索文档"""
    try:
        data_manager = await get_data_manager()
        
        # 执行搜索
        search_results = await data_manager.search_documents(
            query=request.query,
            search_type=request.search_type,
            top_k=request.top_k
        )
        
        # 格式化搜索结果
        results = []
        for result in search_results:
            results.append({
                "doc_id": result.document.id,
                "content": result.document.content,
                "metadata": result.document.metadata,
                "score": result.score,
                "relevance_type": result.relevance_type
            })
        
        return SearchResponse(
            query=request.query,
            results=results,
            total_count=len(results),
            search_type=request.search_type
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Search failed: {str(e)}"
        )

@router.get("/stats")
async def get_storage_stats():
    """获取存储统计信息"""
    try:
        data_manager = await get_data_manager()
        
        stats = await data_manager.get_storage_stats()
        
        return {
            "storage_stats": stats,
            "status": "OK"
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to get stats: {str(e)}"
        )

@router.delete("/documents/{doc_id}")
async def delete_document(doc_id: str):
    """删除文档"""
    try:
        data_manager = await get_data_manager()
        
        success = await data_manager.document_store.delete_document(doc_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Document {doc_id} not found or could not be deleted"
            )
        
        return {
            "doc_id": doc_id,
            "status": "deleted",
            "message": "Document deleted successfully"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to delete document: {str(e)}"
        )

@router.post("/reset")
async def reset_test_data():
    """重置测试数据"""
    try:
        data_manager = await get_data_manager()
        
        # 获取所有文档ID
        doc_ids = await data_manager.document_store.list_documents()
        
        # 删除所有文档
        deleted_count = 0
        for doc_id in doc_ids:
            success = await data_manager.document_store.delete_document(doc_id)
            if success:
                deleted_count += 1
        
        return {
            "status": "reset_complete",
            "deleted_documents": deleted_count,
            "message": f"Reset complete. Deleted {deleted_count} documents."
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to reset test data: {str(e)}"
        )
